package com.yenlien.traceyun.control.service;


import com.yenlien.traceyun.control.dao.BannerDao;
import com.yenlien.traceyun.control.entity.Banner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class BannerService {
    @Autowired
    private BannerDao bannerDao;

    public void save(Banner banner) {
        bannerDao.save(banner);
    }

    public Page<Banner> findByList(final Banner banner) {
        Pageable pageable = PageRequest.of(banner.getPage(), banner.getPageSize());
        return bannerDao.findAll(new Specification<Banner>() {
            private static final long serialVersionUID = 3963941648162858644L;

            public Predicate toPredicate(Root<Banner> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> isUse = root.get("isUse");
                Path<String> projectName = root.get("projectName");
                Path<String> type = root.get("type");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(isUse)) {
                    list.add(cb.equal(isUse, banner.getIsUse()));
                }
                Predicate[] predicate = new Predicate[list.size()];
                Predicate predicateAnd = cb.and(list.toArray(predicate));

                if (banner.getProjectName() != null) {
                    List<Predicate> list2 = new ArrayList<>();
                    if (banner.getProjectName() != null) {
                        list2.add(cb.like(projectName, "%" + banner.getProjectName() + "%"));
                    }
                    if (banner.getType() != null) {
                        list2.add(cb.like(type, "%" + banner.getType() + "%"));
                    }
                    Predicate[] predicateO = new Predicate[list2.size()];
                    Predicate predicateOr = cb.or(list2.toArray(predicateO));
                    return query.where(predicateAnd, predicateOr).getRestriction();
                } else {
                    return predicateAnd;
                }
            }
        }, pageable);
    }

    public Banner findById(String id) {
        return bannerDao.findById(id).get();
    }
}
